<?php
/**
 * 用户登录 注册
 * Create by PhpStorm
 * User: lijia
 * Data: 2020/8/20
 * Time: 17:56
 */

namespace app\api\controller;


use app\api\model\User;
use common\Token;
use EasyWeChat\Factory;
use think\facade\Db;

class Login extends Common
{
    private $loginApp;
    public function __construct()
    {
        parent::__construct();
    }


    /**
     * 初始化微信小程序登录信息
     */
    private function init()
    {
        $config = [
            'app_id' => 'wxc020c739274563c3',
            'secret' => '7c24b6e3b417a09c639b3acf906e8e17',
        ];
        $this->loginApp = Factory::miniProgram($config);
    }

    /**
     * 微信小程序登录
     */
    public function wechatLogin()
    {
        self::init();
        $data = input("request.");
        $code = input("request.code", '', 'trim');
        if (!$code) return json(['code' => 1, 'msg' => '非法请求']);
        $session = $this->loginApp->auth->session($code);
        if (isset($session["session_key"]) && isset($session["openid"])) {
            //返回正常的session_key和openid则算正常登录
            $decry = $this->decryptData('wxc020c739274563c3', $session["session_key"], $data['encryptedData'], $data['iv']);
            $user_id = $this->userIsExists($decry["unionId"],$session["openid"], $data);
            if ($user_id) {
                Db::name('user')->where('user_id', $user_id)->update(['openid' => $session["openid"]]);
                $userData = [
                    'user_id' => $user_id,
                    'exp' => time() + 2592000
                ];
                $token = Token::getToken($userData);
                return resJson(200, 'ok', ['token' => $token]);
            }
            return resJson(0,'数据写入失败');
        } else {
            return resJson(0,'登录失败');
        }
    }


    /**
     * H5 公众号 登录
     * @return \think\response\Json
     */
    public function h5Login()
    {
        $code = input("param.code",'','trim');
        $appId = 'wx58859e594293179b';
        $secret = 'c31e151f716b8229a28b20beeef5bd47';
        // 获取用户 access_token 和 openid
        $uri = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appId.'&secret='.$secret.'&code='.$code.'&grant_type=authorization_code';
        $res = $this->geturl($uri);
        if ($res['refresh_token']){
            // 用unionid 判断该用户是否已存在
            $url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$res["access_token"].'&openid='.$res["openid"].'&lang=zh_CN';
            $userInfo = $this->geturl($url);
            $user = (new User)->getUnionid($userInfo["unionid"]);
            if ($user) {
                $user_id = $user['user_id'];
            } else {
                // 获取用户信息
                $userData['create_time'] = time();
                $userData['photo'] = $userInfo['headimgurl'];
                $userData['username'] = $userInfo['nickname'];
                $userData['sex'] = $userInfo['sex'];
                $userData['openid'] = $userInfo['openid'];
                $userData['unionid'] = $userInfo['unionid'];
                $user_id = (new User())->insertGetId($userData);
            }
            $userData = [
                'user_id' => $user_id,
                'exp' => time() + 2592000
            ];
            $token = Token::getToken($userData);
            return resJson(200, 'ok', ['token' => $token]);
        }else{
            return resJson(0,'获取用户信息失败');
        }
    }

    /**
     * 微信小程序登录
     */
//    public function wechatLogin()
//    {
//        self::init();
//        $data = input("request.");
//        $code = input("request.code", '', 'trim');
//        if (!$code) return json(['code' => 1, 'msg' => '非法请求']);
//        $session = $this->loginApp->auth->session($code);
//        $appId = 'wxc020c739274563c3';
//        $errCode = $this->decryptData($appId, $session['session_key'],$data['encryptedData'],$data['iv']);
//        if(isset($errCode['phoneNumber']) && !empty($errCode['phoneNumber'])) {
//            $data['phoneNumber'] = $errCode['phoneNumber'];
//            $user_id = $this->userIsExists($session['unionid'],$session['openid'], $data);
//            if ($user_id) {
//                $userData = [
//                    'user_id' => $user_id,
//                    'exp' => time() + 2592000,
//                ];
//                $token = Token::getToken($userData);
//                return resJson(200, 'ok', ['token' => $token]);
//            }
//            return resJson(0,'数据写入失败');
//        }else{
//            return resJson(0,'获取手机号码失败');
//        }
//    }


    /**
     * APP登录
     */
    public function appLogin()
    {
        $param = input('param.', '', 'trim');
        $uri = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$param['access_token'].'&openid='.$param['openid'];
        $res = $this->geturl($uri);
        if (!isset($res['openid'])){
            return resJson(0,'登录失败');
        }
        $checkUser = Db::name('user')->where('unionid', $res['unionid'])->find();
        if ($checkUser){
            $user_id = $checkUser['user_id'];
        }else{
            $userData['create_time'] = time();
            $userData['photo'] = $res['headimgurl'];
            $userData['username'] = $res['nickname'];
            $userData['sex'] = $res['sex'];
            $userData['openid'] = $res['openid'];
            $userData['unionid'] = $res['unionid'];
            $user_id = (new User())->insertGetId($userData);
        }
        $userData = [
            'user_id' => $user_id,
            'exp' => time() + 2592000,
        ];
        $token = Token::getToken($userData);
        return resJson(200, 'ok', ['token' => $token]);
    }


    /**
     * IOS假登录
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function iosFalseLogin()
    {
        $userData = [
            'user_id' => 1,
            'exp' => time() + 2592000,
        ];
        $token = Token::getToken($userData);
        return resJson(200, 'ok', ['token' => $token]);
    }

    /**
     * 微信小程序登录数据操作
     */
    private function userIsExists($unionid,$openid,$data)
    {
        $userinfo = (new User)->getUnionid($unionid);
        if ($userinfo) return $userinfo['user_id'];
        $time = time();
        $userData['create_time'] = $time;
        $userData['photo'] = $data['avatarUrl'];
        $userData['username'] = $data['nickName'];
        $userData['sex'] = $data['gender'];
        $userData['openid'] = $openid;
//        $userData['mobile'] = $data['phoneNumber'];
//        $userData['number'] = $data['phoneNumber'];
        $userData['unionid'] = $unionid;
        $user_id = (new User())->insertGetId($userData);
        return $user_id;
    }


    /**
     * 微信信息解密
     * @param string $appid 小程序id
     * @param string $sessionKey 小程序密钥
     * @param string $encryptedData 在小程序中获取的encryptedData
     * @param string $iv 在小程序中获取的iv
     * @return array 解密后的数组
     */
    function decryptData($appid, $sessionKey, $encryptedData, $iv)
    {
        $IllegalAesKey = -41001;
        $IllegalIv = -41002;
        $IllegalBuffer = -41003;
        $DecodeBase64Error = -41004;
        if (strlen($sessionKey) != 24) {
            return $IllegalAesKey;
        }
        $aesKey = base64_decode($sessionKey);
        if (strlen($iv) != 24) {
            return $IllegalIv;
        }
        $aesIV = base64_decode($iv);
        $aesCipher = base64_decode($encryptedData);

        $result = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);

        $dataObj = json_decode($result);
        if ($dataObj == NULL) {
            return $IllegalBuffer;
        }
        if ($dataObj->watermark->appid != $appid) {
            return $DecodeBase64Error;
        }
        $data = json_decode($result, true);
        return $data;
    }


    public function geturl($url){
        $headerArray =array("Content-type:application/json;","Accept:application/json");
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch,CURLOPT_HTTPHEADER,$headerArray);
        $output = curl_exec($ch);
        curl_close($ch);
        $output = json_decode($output,true);
        return $output;
    }


    public function fileinput($str = '测试数据:')
    {
        $date = date('Y-m-d H:i:s');
        $content = "执行日期：" . $date . "\n" . $str . "\n\n";
        $filename = "login.log";
        $handle = fopen($filename,"a+");
        fwrite($handle,$content);
        fclose($handle);
    }

}